package test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class HistogramPanel extends JPanel {

	private int histogramWidth = 320;
	private int histogramHeight = 240;
	private BufferedImage image;

	/**
	 * Create the panel.
	 */
	public HistogramPanel() {
		init();
	}

	private void init() {
		image = new BufferedImage(histogramWidth, histogramHeight,
				BufferedImage.TYPE_4BYTE_ABGR);
	}

	public void setData(int[] statistics, int totalPixels) {
		int max = getMax(statistics);

		Graphics g = image.getGraphics();
		g.clearRect(0, 0, histogramWidth, histogramHeight);
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, histogramWidth, histogramHeight);

		g.setColor(Color.BLACK);
		for (int i = 0; i < statistics.length; i++) {
			g.drawLine(
					i,
					histogramHeight,
					i,
					(int) (histogramHeight * (1 - statistics[i] / (double) max)));
		}

		g.dispose();
		repaint();
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		g.drawImage(image, 0, 0, null);
	}

	private int getMax(int[] arr) {
		int max = 0;
		for (int i : arr) {
			if (i > max) {
				max = i;
			}
		}
		return max;
	}

}
